package cn.com.scitc.licenseplateback.token;

import cn.com.scitc.licenseplateback.dateFormat.DateFormat;
import nl.bitwalker.useragentutils.UserAgent;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class TokenFactory {

    @Autowired
    private DateFormat dateFormat;

    /**
     * 生成 token 键
     *
     * @param id   身份证号
     * @param name 姓名
     * @return
     */
    public String setTokenKey(String id, String name) {
        StringBuilder sb = new StringBuilder();
        id = DigestUtils.md5Hex(id) + "_";
        name = Base64.encodeBase64String(name.getBytes());

        sb.append(id).append(name);
        return sb.toString();
    }

    /**
     * 生成 token 值
     *
     * @param request http请求
     * @return
     */
    public List<Map> setTokenValue(String Account, HttpServletRequest request) {
        List<Map> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();

        String userAgent = request.getHeader("user-agent");
        UserAgent userAgent1 = UserAgent.parseUserAgentString(userAgent);
        if (userAgent1.getOperatingSystem().isMobileDevice()) {
            map.put("Driver", "MOBILE");
        } else {
            map.put("Driver", "PC");
        }

        map.put("loginTime", dateFormat.getCurrentDateTime());

        map.put("userId",Account);

        list.add(map);

        return list;
    }

}
